package http

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"micro-oauth/datamodels/autherror"
	"net/http"
	"time"
)

const (
	SuccessCode = 0
	ErrorCode   = 1
	WarningCode = 2
)

func DurationToStr(duration time.Duration) string {
	return fmt.Sprintf("%dms", uint64(duration/time.Millisecond))
}

func APIWrapper(viewFunc func(*gin.Context) (interface{}, autherror.HexError)) func(c *gin.Context) {
	wrapperFunc := func(c *gin.Context) {
		stInter := c.Value("start_time")
		var st time.Time
		if stInter != nil {
			st = stInter.(time.Time)
		} else {
			st = time.Now()
		}

		result, err := viewFunc(c)
		duration := time.Since(st)
		c.Header("Duration", DurationToStr(duration))
		if err != nil {
			errRes := HexErrorToResponse(err)
			if result != nil{
				errRes[`payload`] = result
			}
			c.JSON(http.StatusOK, errRes)
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"status_code": SuccessCode,
			"payload":     result,
		})
		return
	}
	return wrapperFunc
}
